const ffmpegPath = require('@ffmpeg-installer/ffmpeg').path;
const ffmpeg = require('fluent-ffmpeg');
const fs = require('fs');
const Path = require('path');
const { v4: uuidv4 } = require('uuid'); // 生成视频唯一id

const VideoController = {
  upload: async (req, res) => {
    try {
      console.log(req.file);
      const tempFilePath = Path.resolve(req.file.path); // 视频上传后的临时文件位置
      const videoId = uuidv4(); // 为视频资源创建唯一 ID
      const storageDirectory = Path.resolve('public/video-temp', videoId);
      console.log(tempFilePath);
      //为视频创建储存位置，所有视频切片储存在 ./storage/{videoId} 目录下
      fs.mkdirSync(storageDirectory);
      ffmpeg.setFfmpegPath(ffmpegPath); // 设置程序路径
      await ffmpeg(tempFilePath)
        .videoCodec('libx264')
        .audioCodec('aac')
        .addOption('-hls_time', 10)
        .addOption('-hls_segment_type', 'mpegts')
        .addOption('-hls_list_size', 0)
        .format('hls')
        .addOption('-max_muxing_queue_size', 1024)
        .output(`${storageDirectory}/video.m3u8`)
        .on('start', function () {
          console.log('开始为视频切片');
        })
        .on('end', function () {
          fs.rmSync(tempFilePath); // 删除上传的临时文件
          console.log('切片完成');
          res.send({
            success: true,
            code: 1,
            data: `video-temp/${videoId}/video.m3u8`,
            msg: '上传成功',
          });
        })
        .on('error', function (err) {
          fs.rmSync(tempFilePath); // 删除上传的临时文件
          console.error('切片失败：', err);
          res.send({
            success: false,
            code: 0,
            msg: '切片失败：:' + err,
          });
        })
        .run();

      //返回播放地址
    } catch (error) {
      console.log(error);
      res.send({
        success: false,
        code: 0,
        msg: '上传失败:' + error,
      });
    }
  },
};

module.exports = VideoController;
